package com.authapi.sample.api.controller;

import com.authapi.sample.api.entity.User;
import com.authapi.sample.api.entity.UserRole;
import com.authapi.sample.api.model.Request.RoleUser.RoleUserRequest;
import com.authapi.sample.api.model.Request.RoleUser.UpdateRoleUserRequest;
import com.authapi.sample.api.model.Response.Common.Result;
import com.authapi.sample.api.model.Response.Common.ResultList;
import com.authapi.sample.api.service.impl.MenuServiceImpl;
import com.authapi.sample.api.service.impl.UserRoleServiceImpl;
import com.authapi.sample.api.service.impl.UserServiceImpl;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Baomidou
 * @since 2024-09-26
 */
@RestController
@RequestMapping("/userRole")
public class UserRoleController {
    @Autowired
    private UserRoleServiceImpl userRoleService;
    @Autowired
    private UserServiceImpl userService;
    @GetMapping("/getUserList")
    public ResultList<List<User>> getUserList(String roleId) {
        List<String> userIds = userRoleService
                .query().eq("role_id",roleId).list()
                .stream().map(UserRole::getUserId).collect(Collectors.toList());
        if(userIds.isEmpty()){
            return ResultList.Success(new ArrayList<User>());
        }
        List<User> userList = new ArrayList<>(userService
                .query().in("id", userIds).list());

        return ResultList.Success(userList);
    }

    @PostMapping("/addRoleUser")
    public Result< UserRole> addRoleUser(RoleUserRequest request) {
        UUID uuid = UUID.randomUUID();
        String id = uuid.toString();
        var userRole = new UserRole(){
            {
                setId(id);
                setUserId(request.getUserId());
                setRoleId(request.getRoleId());
            }
        };
        userRoleService.save(userRole);
        return Result.Success(userRole);
    }
    @PostMapping("/UpdateRoleUser")
    public Result< UserRole> UpdateRoleUser(@RequestBody UpdateRoleUserRequest request) {
        List<String> Ids = userRoleService
                .query().eq("role_id",request.roleId).list()
                .stream().map(UserRole::getId).collect(Collectors.toList());
        userRoleService.removeByIds(Ids);

        for(int i=0;i<request.userIds.size();i++){
            UUID uuid = UUID.randomUUID();
            String id = uuid.toString();

            int finalI = i;
            var userRole = new UserRole(){
                {
                    setId(id);
                    setUserId(request.userIds.get(finalI));
                    setRoleId(request.roleId);
                }
            };
            userRoleService.save(userRole);
        }

        return Result.Success(null);
    }

}
